package com.wanjia.gateway.server;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Verification;
import com.wanjia.admin.server.config.security.JwtTokenUtil;
import com.wanjia.project.commons.dto.Consts;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName AuthFilter
 * @Author alan.wang   QQ:3103484396
 * @Description
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    static Algorithm algorithm = Algorithm.HMAC512(Consts.Auth.SECRET);
    static Verification verification = JWT.require(algorithm);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println(path);
        if(path.indexOf("login") == -1) {
            String userToken = JwtTokenUtil.s;
            //如果请求的地址不是登录，需要对身份信息进行验证
            String token = request.getHeaders().get(userToken).get(0);
            try {
                verification.build().verify(token);//对token有效性进行验证
            } catch (Exception e) {
                e.printStackTrace();
                //改变响应的结果吗为401(没有经过认证(登录))
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                //响应到此完成，不再继续向后传递
                return exchange.getResponse().setComplete();
            }
        }
        //响应继续向后传递
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
